package cn.zh.npro.Activity;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.PersistableBundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.pgyersdk.crash.PgyCrashManager;
import com.pgyersdk.javabean.AppBean;
import com.pgyersdk.update.PgyUpdateManager;
import com.pgyersdk.update.UpdateManagerListener;

import java.util.Timer;
import java.util.TimerTask;

import cn.zh.npro.Fragment.ClientFragment;
import cn.zh.npro.Fragment.GoodsFragment;
import cn.zh.npro.Fragment.Homefragment;
import cn.zh.npro.Fragment.MineFragment;
import cn.zh.npro.Fragment.OrderFragment;
import cn.zh.npro.MyApplication;
import cn.zh.npro.R;

public class MainActivity extends BaseActivity {
   Fragment homef,orderf,clientf,goodsf,minef;
   RadioGroup mainrgroup;
   FragmentManager fm;
   MyApplication mapp;
   String uid="";
   String logt="0";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        logt=getIntent().getStringExtra("logt");
        fm=getSupportFragmentManager();
        mapp= (MyApplication) getApplication();
        uid=mapp.getSp().getString("uid","");
        initm();
        PgyCrashManager.register(this);
        PgyUpdateManager.register(MainActivity.this,
                new UpdateManagerListener() {
                    @Override
                    public void onUpdateAvailable(final String result) {
                        // 将新版本信息封装到AppBean中
                      final AppBean  appBean = getAppBeanFromString(result);
                      String sve=getVersion();
                      if (sve.equals(appBean.getVersionName())){
                          return;
                         }
                        new AlertDialog.Builder(MainActivity.this)
                                .setTitle("更新")
                                .setMessage("   检测更新?")
                                .setNegativeButton(
                                        "确定",
                                        new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(
                                                    DialogInterface dialog,
                                                    int which) {
                                                if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                                                    ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                                                } else {
                                                startDownloadTask(MainActivity.this, appBean.getDownloadURL());
                                                }
                                            }
                                        }).show();
                                     }
                    @Override
                    public void onNoUpdateAvailable() {
                    }
                });
            }

    @Override
    protected void onResume() {
        super.onResume();
        if (mapp.isIsld()){
            mapp.setIsld(false);
            SharedPreferences.Editor editor=mapp.getSp().edit();
            editor.clear();
            editor.commit();
            Intent intent=new Intent(MainActivity.this,Login.class);
            startActivity(intent);
            finish();
             }
           }

    public void initm(){
           mainrgroup=findViewById(R.id.mainrgroup);
           mainrgroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
               @Override
               public void onCheckedChanged(RadioGroup radioGroup, int i) {
                   FragmentTransaction ft=fm.beginTransaction();
                   hideAllFragments(ft);
                   switch (i){
                       case R.id.menu_home:
                           if (null==homef){
                               homef = new Homefragment();
                               ft.add(R.id.fram,homef);
                               //如果当前fragment已经被构造，则显示出来
                           }else {
                               ft.show(homef);
                           }
                           break;
                       case R.id.menu_order:
                           if (null==orderf){
                               orderf = new OrderFragment();
                               ft.add(R.id.fram,orderf);
                               //如果当前fragment已经被构造，则显示出来
                           }else {
                               ft.show(orderf);
                           }
                           break;
                       case R.id.menu_custom:
                           if (null==clientf){
                               clientf = new ClientFragment();
                               ft.add(R.id.fram,clientf);
                               //如果当前fragment已经被构造，则显示出来
                           }else {
                               ft.show(clientf);
                           }
                           break;
                       case R.id.menu_goods:
                           if (null==goodsf){
                               goodsf = new GoodsFragment();
                               ft.add(R.id.fram,goodsf);
                               //如果当前fragment已经被构造，则显示出来
                           }else {
                               ft.show(goodsf);
                           }
                           break;
                       case R.id.menu_mine:
                           if (null==minef){
                               minef = new MineFragment();
                               ft.add(R.id.fram,minef);
                               //如果当前fragment已经被构造，则显示出来
                           }else {
                               ft.show(minef);
                           }
                           break;
                        }
                   ft.commit();
                 }
              });
           RadioButton menu_home= (RadioButton) findViewById(R.id.menu_home);
           menu_home.setChecked(true);


         }

    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        }


    private void hideAllFragments(FragmentTransaction ft){
        if (null != homef){ft.hide(homef);}
        if (null != orderf){ft.hide(orderf);}
        if (null != clientf){ft.hide(clientf);}
        if (null != goodsf){ft.hide(goodsf);}
        if (null != minef){ft.hide(minef);}
         }



   boolean mBackKeyPressed=false;
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (!mBackKeyPressed) {
                Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                mBackKeyPressed = true;
                new Timer().schedule(new TimerTask() {
                    @Override
                    public void run() {
                        mBackKeyPressed = false;
                    }
                }, 2000);
                return true;
            } else {
                this.finish();
                System.exit(0);
             }
          }

        return super.onKeyDown(keyCode, event);
       }





    //监听
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode){
            case 0145:
                if(grantResults.length >0 &&grantResults[0]==PackageManager.PERMISSION_GRANTED){
                    //用户同意授权
                }else{
                    //用户拒绝授权
                    //以下为跳转至手机设置界面
                    Intent intent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                    intent.setData(Uri.parse("package:" + getPackageName()));
                    startActivity(intent);
                }
                break;
             }
         }



    // 获取当前版本的版本号
    private String getVersion(){
        try {
            PackageManager packageManager = getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(
                    getPackageName(), 0);
            return packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return "";
           }
        }



  }
